// 和用户相关的状态管理
import { createSlice } from "@reduxjs/toolkit";
import { removeToken, request, setToken as _setToken, getToken } from "@/utils";
import { loginAPI, getProfileAPI } from "@/api/user";

const userStore = createSlice({
  name: "user",
  // 数据状态
  initialState: {
    // token: localStorage.getItem("token_key")  || '',
    token: getToken() || "",
    // 用户信息
    userInfo: {},
  },

  // 同步修改方法
  reducers: {
    setToken(state, action) {
      state.token = action.payload;
      // localstorage存一份
      // localStorage.setItem("token_key",action.payload)
      _setToken(action.payload);
    },
    // 赋值用户信息
    setUserInfo(state, action) {
      state.userInfo = action.payload;
    },

    // 退出的时候把用户信息清除
    clearUserInfo(state) {
      state.token = "";
      state.userInfo = {};
      // 清除本地的token
      removeToken();
    },
  },
});

// 解构出来actionCreater
const { setToken, setUserInfo, clearUserInfo } = userStore.actions;

// 异步请求 完成登录获取token
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    // 1.发送异步请求
    // const res = await request.post("/authorizations", loginForm);

    const res = await loginAPI(loginForm);

    // 2.提交同步action 进行token的储存
    dispatch(setToken(res.data.token));
  };
};

// 异步请求获取用户信息
const fetchUserInfo = () => {
  return async (dispatch) => {
    // const res = await request.get("/user/profile");

    const res = await getProfileAPI();

    //异步储存
    dispatch(setUserInfo(res.data));
  };
};

//获取reducer 函数
const reducer = userStore.reducer;

// 导出函数
export { setToken, fetchLogin, fetchUserInfo, clearUserInfo };

// 默认导出
export default reducer;
